package cn.gzsf.coolshark.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
                                   //在urlPatterns里面配置经过过滤器的路径
@WebFilter(filterName = "MyFilter",urlPatterns = {"/admin.html","/insertBanner.html"})
public class MyFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //因为HttpServletRequest是ServletRequest子类，如果用这个子类，需要强转
        HttpServletRequest req =  (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        //通过request对象拿到session
        HttpSession session = req.getSession();
        //从session对象中拿user对象
        Object user = session.getAttribute("user");
        if(user==null){//未登录
            res.sendRedirect("/login.html");//让客户端重定向到登录页面
        }else {//登录过
            chain.doFilter(request, response);//放行，允许访问资源
        }
    }
}
